#include <stdio.h> 
#include <stdlib.h>
int calculate(int **sum1,int **a1,int **b1,int hang,int lie,int a1lie);

int calculate(int **sum1,int **a1,int **b1,int hang,int lie,int a1lie) {       //矩阵计算函数 
	for(int i = 0; i < hang; ++i)
		for(int j = 0; j < lie; ++j)
			for(int k=0; k < a1lie; ++k)                
				sum1[i][j]+=a1[i][k]*b1[k][j];
	printf("矩阵乘后结果为\n");
    for(int i = 0; i < hang; i++){ 
		for(int j = 0; j < lie; j++)
			printf("%d\t",sum1[i][j]);
		printf("\n");
	} 
}

int main(void) {
	int num1a, num2a, num1b, num2b, num1, num2;
	while(1){ 
	printf("请输入A矩阵的行数：");                            //录入矩阵大小 
	scanf("%d", &num1a);
	printf("请输入A矩阵的列数：");
	scanf("%d", &num2a);
	printf("请输入B矩阵的行数：");
	scanf("%d", &num1b);
	printf("请输入B矩阵的列数：");
	scanf("%d", &num2b);
	if(num2a == num1b)break;
	else {printf("矩阵无法相乘\n请重新输入\n");              //判断矩阵是否可以相乘 
	continue;
	}} 
	int **a = (int**)calloc(num1a, sizeof(int));             //动态分配二维数组存放矩阵数据 
	for (int i = 0; i < num1a; i++)
		a[i] = (int*)calloc(num1b, sizeof(int));
	int **b = (int**)calloc(num2a, sizeof(int));
	for (int j = 0; j < num2a; j++)
		b[j] = (int*)calloc(num2b, sizeof(int));
	getchar();
	printf("请输入矩阵A中的元素（请逐个逐行输入）：");        //输入矩阵A 
	for (int k = 0; k < num1a; k++)
		for (int m = 0; m < num2a; m++)
			scanf("%d", &a[k][m]);
	printf("请输入矩阵B中的元素（请逐个逐行输入）：");		  //输入矩阵B
	for (int n = 0; n < num1b; n++)
		for (int o = 0; o < num2b; o++)
			scanf("%d", &b[n][o]);
	int **sum = (int**)calloc(num1a, sizeof(int));            //由矩阵A、矩阵B确定相乘后矩阵C的大小 
	for (int p = 0; p < num1a; p++)
		sum[p] = (int*)calloc(num2b, sizeof(int));
	calculate(sum,a,b,num1a,num2b,num2a);					  //调用矩阵计算函数，并输出 
	return 0;
}
